using System;

namespace ThalesHsmComms
{
	public class WSMMsg
	{
		protected String commandCode;
		protected String responseCode;
		protected String errorCode;
		protected byte[] requestData;
		protected string responseData;
		protected int currentIndex;

		public bool IsSuccessful{
			get{
				return this.errorCode.Equals("00",StringComparison.Ordinal);
			}
		}

		public byte[] Request{
			get{
				return requestData;
			}
		}

		public string Response{
			get{
				return this.responseData;
			}
		}

		public String ErrorCode{
			get{
				return errorCode;
			}
		}

		public WSMMsg (string cmd)
		{
			this.commandCode = cmd;
			this.currentIndex = 0;
		}

		public string GetNextBytesFromResponse(int num) 
		{
			string retData = "";

			for (int i = 0; i < num; i++) 
			{
				retData += responseData[currentIndex++];
			}

			return retData;
		}

		public void ResetIndex(){
			currentIndex=0;
		}

		virtual protected void Encode()
		{
			throw new NotImplementedException("Encode of base class called. WSMMsg");
		}

		virtual protected void Decode()
		{
			throw new NotImplementedException("Decode of base class called. WSMMsg");
		}

		public void SendToHsm(HsmConnection conn)
		{
			if(!conn.IsConnected)
			{
				conn.Connect();
			}

			this.Encode();
			this.responseData = conn.SendRecv(this.Request);

			// get response code
			this.responseCode = this.GetNextBytesFromResponse(2);	
			// get error code
			this.errorCode = this.GetNextBytesFromResponse(2);
			if (!this.errorCode.Equals("00") && !this.errorCode.Equals("01"))
				return;

			this.Decode();

		}

	}
}

